**Caculate Weighting
do "E:\yungyu\lottery_baby\do\set_environment.do"


capture log close
log using "$log\3.2.calculating_weights_single_age_`c(current_date)'.log" , replace
clear
set more off


clear
**Append 母體檔
forv i = 96(1)101{
	append using "$wdata/population_`i'.dta", force
}

gen population = 1

gen win_age = age

set seed 20230731
gen random = rnormal()
sort pers_idn random
duplicates drop pers_idn, force

save "$wdata/population.dta", replace


use "$wdata/population.dta", replace

		
	foreach x of varlist pers_income-pers_earnings spouse_income-spouse_earnings{
		replace `x' = `x' / 1000
	}
	
		** Household variables
		foreach var in income earnings asset liquidasset saving{
			gen avg_`var' = pers_`var' if spouse_idn == ""
			replace avg_`var' = (pers_`var' + spouse_`var')/2 if spouse_idn ~= ""
		}
		
	
save "$wdata/population.dta", replace		




use "$wdata/population.dta", clear
ap using "$wdata\project_lottery_fertility_b3a6_first_5k.dta", force
drop if prize10M >= 15 & population != 1

keep if norm == -1 | norm == .
recode population . = 0
gen sample = population == 0

/*
sum pers_asset ,d
sum avg_asset ,d

sum pers_earnings ,d
sum avg_earnings ,d

sum pers_income ,d
sum avg_income ,d
*/	

foreach var in pers_asset avg_asset{

	gen `var'_grp=.
	replace `var'_grp=0 if `var'<0
	replace `var'_grp=1 if `var'==0	
	replace `var'_grp=2 if `var'>0 		& `var'<=100 // 0-10萬
	replace `var'_grp=3 if `var'>100	& `var'<=500  // 10萬-50萬
	replace `var'_grp=4 if `var'>500	& `var'<=1000  // 50萬-100萬	
	replace `var'_grp=5 if `var'>1000	& `var'<=3000  // 100萬-200萬
	replace `var'_grp=6 if `var'>3000	& `var'<=5000  // 200萬-500萬	
	replace `var'_grp=7 if `var'>5000	& `var'<=10000   // 500萬-1000萬
	replace `var'_grp=8 if `var'>10000	  // 1000萬	
	tab `var'_grp
}


foreach var in pers_earnings avg_earnings pers_income avg_income{

	gen `var'_grp=.
	replace `var'_grp=1 if `var'<=0
	replace `var'_grp=2 if `var'>0 		& `var'<=100 // 0-10萬
	replace `var'_grp=3 if `var'>100	& `var'<=200  // 10萬-20萬	
	replace `var'_grp=4 if `var'>200	& `var'<=300  // 20萬-30萬
	replace `var'_grp=5 if `var'>300	& `var'<=500  // 30萬-50萬	
	replace `var'_grp=6 if `var'>500	& `var'<=800  // 50萬-80萬		
	replace `var'_grp=7 if `var'>800	& `var'<=1000  // 80萬-100萬
	replace `var'_grp=8 if `var'>1000	& `var'<=1500  // 100萬-150萬	
	replace `var'_grp=9 if `var'>1500   // 150萬以上
	tab `var'_grp
}


gen count = 1
gen pers_labor = pers_earnings > 0
gen avg_labor  = avg_earnings>0	


collapse (sum) count, by(win_age pers_earnings_grp pers_asset_grp married population)
reshape wide count, i(win_age pers_earnings_grp pers_asset_grp married) j(population)
gen weight = count1/count0

keep win_age pers_earnings_grp pers_asset_grp married weight 

save "$wdata\reweight_earn_asset.dta", replace
